import os
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
import cv2
# video_file =  '/home/sean/data/UWdevkit/ImageSets/train_video.txt'
video_list = [['seastar', 100],]
img_path = '/home/sean/data/UWdevkit/extra/Data/train/'
anno_path = '/home/sean/data/UWdevkit/extra/Annotations/train/'

i = 0
# for line in open(video_file, 'r'):
for line in video_list:
    # video, video_size = line.split(' ')
    video, video_size = line
    anno_in_video_path = os.path.join(anno_path, video)
    # print(anno_in_video_path)
    files = os.listdir(anno_in_video_path)
    file_first_name = files[0].split('.')[0].split('_')[0]
    # if file_first_name[0] == 'q':
    #     file_first_name = file_first_name + '_RUAS'

    # print(file_first_name)
    file_num = [int(file.split('.')[0].split('_')[-1]) for file in files]
    ordered_file_num = sorted(file_num)

    new_ordered_file_num = list(range(len(ordered_file_num)))
    # print(new_ordered_file_num)

    for old_num, new_num in zip(ordered_file_num, new_ordered_file_num):
        if old_num != new_num:
            if file_first_name in ['val', 'trepang', 'echinus']:
                num_str = str(old_num).zfill(4)
            else:
                num_str = str(old_num)
            old_xml_name = os.path.join(anno_path, video, file_first_name+'_'+num_str+'.xml')
            new_xml_name = os.path.join(anno_path, video, str(new_num).zfill(6)+'.xml')
            old_img_name = os.path.join(img_path, video, file_first_name+'_'+num_str + '.JPEG')
            new_img_name = os.path.join(img_path, video, str(new_num).zfill(6) + '.jpg')
            os.rename(old_xml_name, new_xml_name)
            os.rename(old_img_name, new_img_name)
            print(old_img_name, new_img_name)
            print(old_xml_name, new_xml_name)
            i += 1
print(i)


# i = 0
# for file in os.listdir(path):
#     if os.path.isfile(os.path.join(path,file)) == True:
#         name = file.split('.')
#         if name[1] != 'jpg' and name[1] != 'xml':
#             name[1] = 'jpg'
#         name[0] = 'Video5_' + name[0]
#         # i = i+1
#         newname = name[0] + '.'+ name[1]
#         os.rename(os.path.join(path, file), os.path.join(path,newname))
#         print(file, 'rename ok')
